package com.hmall.item.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.databind.util.JSONPObject;
import com.hmall.common.pojo.dto.ItemPageDto;
import com.hmall.common.pojo.dto.PageDTO;
import com.hmall.item.mapper.ItemMapper;
import com.hmall.item.pojo.Item;
import com.hmall.item.pojo.dto.ItemSaveDto;
import com.hmall.item.service.IItemService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.UUID;

@Slf4j
@Service
public class ItemService extends ServiceImpl<ItemMapper, Item> implements IItemService {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 分页查询
     *
     * @param itemPageDto
     * @return
     */
    @Override
    public PageDTO<Item> getPage(ItemPageDto itemPageDto) {
        Page<Item> page = new Page<>(itemPageDto.getPage(), itemPageDto.getSize());
        baseMapper.selectPage(page, null);
        baseMapper.selectPage(
                page,
                new LambdaQueryWrapper<Item>()
                        .orderByDesc(Item::getUpdateTime)
        );
        return PageDTO.<Item>builder()
                .total(page.getTotal())
                .list(page.getRecords())
                .build();
    }

    /**
     * 上架，下架商品
     *
     * @param id
     * @param status
     */
    @Override
    public void status(Long id, Integer status) {
        baseMapper.updateById(
                Item.builder()
                        .id(id)
                        .status(status)
                        .build()
        );

        // 2下架的商品,es删除存储，1上架的反之
        //生产者确认信息

        if (2 == status)
            rabbitTemplate.convertAndSend("es.item", "remove", id, correlationData());
        else
            rabbitTemplate.convertAndSend("es.item", "add", JSONObject.toJSONString(baseMapper.selectById(id)), correlationData());
    }

    @Override
    public void save(ItemSaveDto itemSaveDto) {
        // 属于sku，规格格式   {"规格属性":"规格值"}，格式不对不显示
        log.info("添加商品信息：{}", itemSaveDto);
        Item item = new Item();
        BeanUtils.copyProperties(itemSaveDto, item);

        baseMapper.insert(item);

        // 添加到es
        rabbitTemplate.convertAndSend("es.item", "add", JSONObject.toJSONString(item), correlationData());
    }

    private CorrelationData correlationData() {
        CorrelationData correlationData = new CorrelationData(UUID.randomUUID().toString());
        correlationData.getFuture().addCallback(
                result -> {
                    if(result.isAck()){
                        // 3.1.ack，消息成功
                        log.info("消息发送成功, ID:{}", correlationData.getId());
                    }else{
                        // 3.2.nack，消息失败
                        log.error("消息发送失败, ID:{}, 原因{}",correlationData.getId(), result.getReason());
                    }
                },
                ex -> log.error("消息发送异常, ID:{}, 原因{}",correlationData.getId(),ex.getMessage())
        );

        return correlationData;
    }
}
